//
//  DataBase.m
//  Lesson-UI-19-Question1
//
//  Created by lanou3g on 15/11/26.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "DataBase.h"
#import <sqlite3.h>
#import "UserInformation.h"
//#import "Student.h"

static DataBase *dataBase = nil;

@implementation DataBase

+ (DataBase *)sharedDataBase
{
    if (nil == dataBase) {
        dataBase = [[DataBase alloc] init];
    }
    return dataBase;
}


#pragma mark - 将数组归档
+ (NSData *)dataOfArray:(NSMutableArray *)Array forKey:(NSString *)key
{
    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    
    [archiver encodeObject:Array forKey:key];
    [archiver finishEncoding];
    return data;
}
#pragma mark - 反归档
+ (NSMutableArray *)unarchiverObject:(NSData *)data forKey:(NSString *)key
{
    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    NSMutableArray *object = [unArchiver decodeObjectForKey:key];
    [unArchiver finishDecoding];
    return object;
}


static sqlite3 *db = nil;
#pragma mark - 打开数据库
- (void)openDB
{
    if (nil != db) {
        return;
    }
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [document stringByAppendingPathComponent:[NSString stringWithFormat:@"Douban.sqlite"]];
    NSLog(@"%@",filePath);
    int result = sqlite3_open([filePath UTF8String], &db);
    if (result == SQLITE_OK) {
        NSString *sql = [NSString stringWithFormat:@"CREATE TABLE Douban (userName TEXT,password TEXT,telephone TEXT,email TEXT,movieArray BLOB,Activity BLOB)"];
        sqlite3_exec(db, [sql UTF8String], nil, nil, nil);
        NSLog(@"数据库打开成功");
    }else{
        NSLog(@"%d",result);
    }
}

#pragma mark - 添加用户
- (void)insertUserInformation:(UserInformation *)userInformation
{
    [self openDB];
    sqlite3_stmt *stmt = nil;
    NSString *sql = @"INSERT INTO Douban (userName,password,telephone,email,movieArray,Activity) VALUES (?,?,?,?,?,?)";
    int result = sqlite3_prepare(db,[sql UTF8String] , -1, &stmt, NULL);
    if (result == SQLITE_OK) {
        sqlite3_bind_text(stmt, 1, [userInformation.uesrName UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2, [userInformation.password UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 3, [userInformation.telephone UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 4, [userInformation.email UTF8String], -1, NULL);

        NSData *movieData = [DataBase dataOfArray:userInformation.movieAarry forKey:@"movieArray"];
        NSData *activityData = [DataBase dataOfArray:userInformation.Activity forKey:@"activity"];
        sqlite3_bind_blob(stmt, 5, [movieData bytes], (int)[movieData length], NULL);
        sqlite3_bind_blob(stmt, 6, [activityData bytes], (int)[activityData length], NULL);
        sqlite3_step(stmt);
        sqlite3_finalize(stmt);
        NSLog(@"添加用户成功");
    }else{
        NSLog(@"=======添加用户失败 %d",result);
    }
}
#pragma mark - 更新数据库
- (void)updataUserInformationMovieArray:(NSMutableArray *)movieArray activity:(NSMutableArray *)activity withUserName:(NSString *)userName
{
    [self openDB];
    sqlite3_stmt *stmt = nil;
    NSString *sql = @"UPDATE Douban SET movieArray = ? ,activity = ? WHERE userName = ? ";
    int result = sqlite3_prepare(db, [sql UTF8String], -1, &stmt, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"%@",movieArray);
        NSData *movieData = [DataBase dataOfArray:movieArray forKey:@"movieArray"];
        NSLog(@"%@",[DataBase unarchiverObject:movieData forKey:@"movieArray"]);
        NSData *activityData = [DataBase dataOfArray:activity forKey:@"activity"];
        sqlite3_bind_blob(stmt, 1, [movieData bytes], (int)[movieData length], NULL);
        sqlite3_bind_blob(stmt, 2, [activityData bytes], (int)[activityData length], NULL);
        sqlite3_bind_text(stmt, 3, [userName UTF8String], -1, NULL);
        sqlite3_step(stmt);
        sqlite3_finalize(stmt);
        NSLog(@"更新成功");
    }else{
        NSLog(@"更新失败 %d",result);
    }
}
//根据用户名查找信息
- (UserInformation *)selectInformationWithUserName:(NSString *)userName
{
    [self openDB];
    sqlite3_stmt *stmt = nil;
    NSString *sql = @"SELECT *FROM Douban WHERE userName = ?";
    int result = sqlite3_prepare(db, [sql UTF8String], -1, &stmt, NULL);
    if (result == SQLITE_OK) {
        sqlite3_bind_text(stmt, 1, [userName UTF8String], -1, NULL);
        UserInformation *userInformation = [[UserInformation alloc] init];
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            NSString *userName = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 0)];
            NSString *password = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
            NSString *telephone = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 2)];
            NSString *email = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 3)];
            NSData *dataMovie = [NSData dataWithBytes:sqlite3_column_blob(stmt, 4) length:sqlite3_column_bytes(stmt, 4)];
            
            NSMutableArray *arrMovie = (NSMutableArray *)[DataBase unarchiverObject:dataMovie forKey:@"movieArray"];
            NSLog(@"%@",arrMovie);
            NSData *dataActivity = [NSData dataWithBytes:sqlite3_column_blob(stmt, 5) length:sqlite3_column_bytes(stmt, 5)];
            NSMutableArray *arrActivity = (NSMutableArray *)[DataBase unarchiverObject:dataActivity forKey:@"activity"];
            userInformation.uesrName = userName;
            userInformation.password = password;
            userInformation.telephone = telephone;
            userInformation.email = email;
            userInformation.movieAarry = arrMovie;
            userInformation.Activity = arrActivity;
            
        }
        sqlite3_finalize(stmt);
        
        NSLog(@"====查找成功");
        return userInformation;
    }else {
        NSLog(@"查找失败,%d",result);
    }
    return nil;

}
- (NSArray *)seleAllUserInformations
{
    [self openDB];
    sqlite3_stmt *stmt = nil;
    NSString *sql = @"SELECT *FROM Douban";
    int resule = sqlite3_prepare(db, [sql UTF8String], -1, &stmt, NULL);
    if (resule == SQLITE_OK) {
        NSMutableArray *arr = [NSMutableArray array];
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            NSString *userName = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 0)];
            NSString *password = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
            NSString *telephone = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 2)];
            NSString *email = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 3)];
            NSData *dataMovie = [NSData dataWithBytes:sqlite3_column_blob(stmt, 4) length:sqlite3_column_bytes(stmt, 4)];
            NSMutableArray *arrMovie = [DataBase unarchiverObject:dataMovie forKey:@"movieArray"];
            NSData *dataActivity = [NSData dataWithBytes:sqlite3_column_blob(stmt, 5) length:sqlite3_column_bytes(stmt, 5)];
            NSMutableArray *arrActivity = [DataBase unarchiverObject:dataActivity forKey:@"activity"];
            UserInformation *userInformation = [[UserInformation alloc] initWithUserName:userName password:password telephone:telephone email:email movieAarry:arrMovie activity:arrActivity];
            [arr addObject:userInformation];
        }
        sqlite3_finalize(stmt);
        NSLog(@"查找所有成功");
        return arr;
    }else{
        NSLog(@"查找所有失败");
    }
    return nil;
}

- (void)CloseDB
{
    if (nil == db) {
        return;
    }
    int result = sqlite3_close(db);
    if (result == SQLITE_OK) {
        NSLog(@"数据库关闭成功");
        db = nil;
    }else{
        NSLog(@"数据库关闭失败");
    }
}

@end
